<template>
  <div>
     <!-- 面包屑部分 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片部分 -->
    <el-card>
      <!-- 头部警告消息 -->
      <el-row>
        <el-col>
           <el-alert
              title="注意：只允许为第三级分类设置相关参数！"
              type="warning"
              show-icon>
            </el-alert>
        </el-col>
      </el-row>
      <!-- 选择分类部分 -->
      <el-row style="margin-top: 10px">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
          clearable
          v-model="selectParId"
            :options="cateList"
            :props="addProps"
            @change="selectIdChange"></el-cascader>
        </el-col>
      </el-row>
      <!-- tab面板 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-row>
            <el-col>
              <el-button type="primary" :disabled="selectParId.length !== 3" @click="addParams">添加参数</el-button>
            </el-col>
          </el-row>
          <el-table
            :data="goodParams"
            style="width: 100%">
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-row>
                  <el-tag
                    v-for="(tag, i) in scope.row.attr_vals"
                    :key="i"
                    closable
                    @close="removePar(scope.row, i)">
                    {{tag}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index">
            </el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数">
            </el-table-column>
            <el-table-column
              label="操作">
              <template v-slot="scope">
                <el-button type="primary" size="mini" class="el-icon-edit" @click="editManyPar(scope.row)">修改</el-button>
                <el-button type="danger" size="mini" class="el-icon-delete" @click="delManyPar(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
            <el-row>
              <el-col>
                <el-button type="primary" :disabled="selectParId.length !== 3" @click="addParams">添加属性</el-button>
              </el-col>
            </el-row>
         <el-table
            :data="goodParams"
            style="width: 100%">
            <el-table-column type="expand">
              <template v-slot="scope">
                <el-row>
                  <el-tag
                    v-for="(tag, i) in scope.row.attr_vals"
                    :key="i"
                    closable
                    @close="removePar(scope.row, i)">
                    {{tag}}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数">
            </el-table-column>
            <el-table-column
              label="操作">
              <template v-slot="scope">
                <el-button type="primary" size="mini" class="el-icon-edit" @click="editManyPar(scope.row)">修改</el-button>
                <el-button type="danger" size="mini" class="el-icon-delete" @click="delManyPar(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog
      :title="'添加' + title"
      :visible.sync="dialogVisible"
      width="30%"
      @close="handleClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item :label="title" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addBtn">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data () {
    return {
      cateList: [],
      addProps: {
        expandTrigger: 'hover',
        children: 'children',
        label: 'cat_name',
        value: 'cat_id'
      },
      // 级联选择器选中的父级分类id数组
      selectParId: [],
      // 参数列表数据
      goodParams: [],
      // tab默认选中项
      activeName: 'many',

      // 添加参数对话框
      dialogVisible: false,
      // 添加对话框的输入内容
      addForm: {
        attr_name: ''
      },
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  computed: {
    title () {
      return this.activeName === 'many' ? '动态参数' : '静态属性'
    }
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取分类信息失败')
      this.cateList = res.data
    },
    selectIdChange () {
      if (this.selectParId.length < 3) {
        this.selectParId = []
        this.goodParams = []
      } else {
        this.getGoodsParams()
      }
    },
    // 根据ID获取商品参数信息
    async getGoodsParams () {
      const { data: res } = await this.$http.get(`categories/${this.selectParId[this.selectParId.length - 1]}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取参数列表失败')
      // 对返回数据进行处理，将attr_vals切割成数组，便于渲染tag
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals === '' ? item.attr_vals = [] : item.attr_vals.split(',')
        // 为每一个输入框添加单独的visible/model
        item.inputVisible = false
        item.inputValue = ''
      })
      this.goodParams = res.data

      console.log(res)
    },
    handleClick () {
      this.getGoodsParams()
    },
    // tag添加按钮点击事件
    showInput (info) {
      info.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // tag添加的提交事件
    handleInputConfirm (info) {
      if (info.inputValue.trim().length === 0) {
        info.inputVisible = false
        info.inputValue = ''
        return
      }

      info.attr_vals.push(info.inputValue.trim())
      info.inputVisible = false
      info.inputValue = ''
      // 发送请求，提交修改
      this.saveAttrVals(info)
    },
    async saveAttrVals (info) {
      const { data: res } = await this.$http.put(`categories/${this.selectParId[this.selectParId.length - 1]}/attributes/${info.attr_id}`, {
        attr_vals: info.attr_vals.join(','),
        attr_sel: info.attr_sel,
        attr_name: info.attr_name
      })
      if (res.meta.status !== 200) return this.$message.error('更新属性失败')
      this.$message.success('更新属性成功')
    },
    // tag的关闭事件
    removePar (info, index) {
      // 根据索引值删除属性值
      info.attr_vals.splice(index, 1)
      this.saveAttrVals(info)
    },
    // 修改删除事件
    editManyPar () {},
    delManyPar () {},
    // 添加按钮的点击事件
    addParams () {
      this.dialogVisible = true
    },
    // 添加参数对话框的关闭事件
    handleClose () {
      this.$refs.addFormRef.resetFields()
      this.addForm = {
        attr_name: ''
      }
    },
    // 添加对话框的提交事件
    async addBtn () {
      const { data: res } = await this.$http.post(`categories/${this.selectParId[this.selectParId.length - 1]}/attributes`, {
        attr_name: this.addForm.attr_name,
        attr_sel: this.activeName
      })
      console.log(res)
      if (res.meta.status !== 201) return this.$message.error('添加参数失败')
      this.$message.success('添加参数成功')
      this.getGoodsParams()
      this.dialogVisible = false
    }
  }
}
</script>

<style scoped lang="less">
 .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
